package view;

import util.Controller;

import javax.swing.*;
import java.awt.*;
import java.util.List;

//豌豆射手子弹类
public class Bullet extends JLabel implements Runnable{

    private int x;
    private int y;
    private int r;
    int damage = 1 ;
    int speed = 5;
    private Controller controller;
    ImageIcon img = new ImageIcon("img\\Bullets\\PeaShooter.png");

    private boolean touchZombie(){
        List<Zombie> zombies = controller.getZombieLists().get(r);
        if (zombies.isEmpty())
            return false;
        for (Zombie zombie:zombies){
            int dis = Math.abs(x-40-zombie.getX());
            if (dis<25){
                zombie.getHurt();
                return true;
            }
        }
        return false;
    }

    public Bullet(int r,int c,Controller controller){
        this.x = 80 * c + 70;
        this.y = 100 * r + 90;
        this.r = r;
        this.controller = controller;
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(img.getImage(), 0, 0,  null);
    }

    @Override
    public void run() {
        controller.getLayeredPane().add(this, new Integer(123+r));
        this.setVisible(true);
        while (x<800){
            if (touchZombie()){ //碰撞
                try {
                    img = new ImageIcon("img\\Bullets\\PeaShooterHit.png");
                    this.repaint();
                    this.setBounds(x+35, y+5,
                            img.getIconWidth(), img.getIconHeight());
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }
            try {
                this.setBounds(x, y,
                        img.getIconWidth(), img.getIconHeight());
                Thread.sleep(10);
                x += 2;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.setVisible(false);
    }
}